import { Platform } from "react-native";
import { MMKV } from "react-native-mmkv";

const isWeb = Platform.OS === "web";
const isWindow = typeof window !== "undefined";
const memoryStorage = new Map<string, string>();
const mmkv = isWeb ? null : new MMKV();

export const syncStorage = {
  getItem: (key: string): string | null => {
    if (isWeb) {
      if (isWindow) {
        return window.localStorage.getItem(key);
      }
      return memoryStorage.get(key) || null;
    } else {
      return mmkv?.getString(key) ?? null;
    }
  },
  
  setItem: (key: string, value: string): void => {
    if (isWeb) {
      if (isWindow) {
        window.localStorage.setItem(key, value);
      } else {
        memoryStorage.set(key, value);
      }
    } else {
      mmkv?.set(key, value);
    }
  },
  
  removeItem: (key: string): void => {
    if (isWeb) {
      if (isWindow) {
        window.localStorage.removeItem(key);
      } else {
        memoryStorage.delete(key);
      }
    } else {
      mmkv?.delete(key);
    }
  },
  
  clear: (): void => {
    if (isWeb) {
      if (isWindow) {
        window.localStorage.clear();
      } else {
        memoryStorage.clear();
      }
    } else {
      mmkv?.clearAll();
    }
  },
};

export const storage = {
  getItem: async (key: string): Promise<string | null> => {
    return Promise.resolve(syncStorage.getItem(key));
  },
  
  setItem: async (key: string, value: string): Promise<void> => {
    syncStorage.setItem(key, value);
    return Promise.resolve();
  },
  
  removeItem: async (key: string): Promise<void> => {
    syncStorage.removeItem(key);
    return Promise.resolve();
  },
  
  clear: async (): Promise<void> => {
    syncStorage.clear();
    return Promise.resolve();
  },
};

export default storage;